查看原文
其他

View事件分发、滑动冲突 详解

胡飞洋 胡飞洋 2022-07-18

目录

一、事件分发

1、事件传递规则

2、源码分析

1)Activity的分发过程:

2)顶级View(ViewGroup)的分发过程:分发规则的伪代码来源的详细说明

3)view的处理过程:主要是onTouchListener、OnTouchEvent、onClick的关系

二、滑动冲突

1、冲突场景

2、解决原理

3、举个例子



View的事件分发,指的是 在多层级ViewGroup/View中对触摸事件的分发。触摸事件即MotionEvent,系统要把它传递给具体的view取处理。

事件序列,从Down开始,到多个Move,再到Up结束,就是一个事件序列。


一、事件分发


1、事件传递规则


事件分发主要3个方法:

  • public boolean dispatchTouchEvent(MotionEvent ev),负责事件的传递分发,事件到达view时一定回调此方法。返回值表示是否消费此事件,受onTouchEvent和子view的dispatchTouchEvent返回值影响。

  • public boolean onInterceptTouchEvent(MotionEvent ev),用于判断是否拦截事件,也是返回值的含义。在dispatchTouchEvent内部调用。view拦截了某个事件,那后续这一事件序列都会默认拦截,不再调用此方法

  • public boolean onTouchEvent(MotionEvent event),用于处理事件,返回值表示是否消费此事件。


在dispatchTouchEvent内部调用。如果不消耗某一事件,那当前view不再接受同一事件序列的事件。注意,如果设置了onTouchListener且onTouch返回值是true,那么不会调用onTouchEvent(会给父view处理)onTouchEvent中发现设置了onClickListener那onCLick会被调用


三者关系:事件到达view时,会调用dispatchTouchEvent,然后内部调用onInterceptTouchEvent判断是否拦截,如果不拦截就调用子view的dispatchTouchEvent。伪代码表示:

public boolean dispatchTouchEvent(MotionEvent event){ boolean consumed; if (onIntercepterTouchEvent(event)){ consumed = onTouchEvent(event); }else { consumed = child.dispatchTouchEvent(event); }
return consumed; }


事件发生时,传递顺序是:Activity-Window-View如果所有activity的所有子View都不处理,那么最终Activity的onTouchEvent会被调用。

另外几点规则:

  1. ViewGroup默认不拦截任何事件。即onInterceptTouchEvent方法返回false

  2. View没有onInterceptTouchEvent()

  3. View的onTouchEvent默认会消耗事件(返回True),除非它是不可点击的——-clickable 和 longClickable同时为false.注意:View的longClickable默认都为false,clickable要根据控件属性判断。

  4. View的enable属性不影响onTouchEvent的默认返回值。(哪怕是disable)

  5. 事件重视先传递给父元素,然后由父元素分发给子View.通过requestDisallowIntercept()分发可以在子元素中干预父元素的事件分发过程,但是ACTION_DOWN事件除外。


2、源码分析


1)Activity的分发过程:

public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } //调用window的superDispatchTouchEvent来分发。(实际window只有一个实现PhoneWindow) if (getWindow().superDispatchTouchEvent(ev)) { return true; } //如果window内所有view没有消费,就会走acticity的onTouchEvent return onTouchEvent(ev);    }

看PhoneWindow:

// This is the top-level view of the window, containing the window decor. private DecorView mDecor;
@Override public boolean superDispatchTouchEvent(MotionEvent event) { //mDecor是DecorView return mDecor.superDispatchTouchEvent(event); }

看DecorView:

public boolean superDispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); }

继续跟就到了ViewGroup的dispatchTouchEvent。DecorView内部的子View实际就是StatusBar、ActionBar、ContengView这些。


2)顶级View(ViewGroup)的分发过程:分发规则的伪代码来源的详细说明

@Override public boolean dispatchTouchEvent(MotionEvent ev) { ...
boolean handled = false; if (onFilterTouchEventForSecurity(ev)) { final int action = ev.getAction(); final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down. // 事件DOWN时会清除 子view的 "不允许父view拦截"的flag。因为Down事件是事件序列的开始,一定会询问本身是否拦截。 if (actionMasked == MotionEvent.ACTION_DOWN) { // Throw away all previous state when starting a new touch gesture. // The framework may have dropped the up or cancel event for the previous gesture // due to an app switch, ANR, or some other state change. cancelAndClearTouchTargets(ev); resetTouchState(); }
// Check for interception. final boolean intercepted; //是Down 或者 MOVE、UP但没有拦截DOWN让子View处理了(mFirstTouchTarget != null) if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) { final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; if (!disallowIntercept) { //如果子View没有不允许拦截,就正常询问自己是否拦截 intercepted = onInterceptTouchEvent(ev); ev.setAction(action); // restore action in case it was changed } else { //如果子View设置了不允许拦截,就不拦截 intercepted = false; } } else { // There are no touch targets and this action is not an initial down // so this view group continues to intercept touches. //不是Down且子view没有处理,就是说本身拦截了DOWN,那后续的MOVE、UP就不再调用onInterceptTouchEvent询问,直接拦截。 intercepted = true; }
// If intercepted, start normal event dispatch. Also if there is already // a view that is handling the gesture, do normal event dispatch. if (intercepted || mFirstTouchTarget != null) { ev.setTargetAccessibilityFocus(false); }
// Check for cancelation. final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed. final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0; TouchTarget newTouchTarget = null; boolean alreadyDispatchedToNewTouchTarget = false;
//如果没有拦截 if (!canceled && !intercepted) {
...
if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { final int actionIndex = ev.getActionIndex(); // always 0 for down final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS;
// Clean up earlier touch targets for this pointer id in case they // have become out of sync. removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount; if (newTouchTarget == null && childrenCount != 0) { final float x = ev.getX(actionIndex); final float y = ev.getY(actionIndex); // Find a child that can receive the event. // Scan children from front to back. final ArrayList<View> preorderedList = buildTouchDispatchChildList(); final boolean customOrder = preorderedList == null && isChildrenDrawingOrderEnabled(); final View[] children = mChildren;
//就遍历子view for (int i = childrenCount - 1; i >= 0; i--) { final int childIndex = getAndVerifyPreorderedIndex( childrenCount, i, customOrder); final View child = getAndVerifyPreorderedView( preorderedList, children, childIndex);
...
//判断子view能否接受事件:是否在播动画、是否点击在区域内 if (!canViewReceivePointerEvents(child) || !isTransformedTouchPointInView(x, y, child, null)) { ev.setTargetAccessibilityFocus(false); continue; }
newTouchTarget = getTouchTarget(child); if (newTouchTarget != null) { // Child is already receiving touch within its bounds. // Give it the new pointer in addition to the ones it is handling. newTouchTarget.pointerIdBits |= idBitsToAssign; break; }
resetCancelNextUpFlag(child);
//child不为空就会调child.dispatchTouchEvent(event) if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { // Child wants to receive touch within its bounds. mLastTouchDownTime = ev.getDownTime(); if (preorderedList != null) { // childIndex points into presorted list, find original index for (int j = 0; j < childrenCount; j++) { if (children[childIndex] == mChildren[j]) { mLastTouchDownIndex = j; break; } } } else { mLastTouchDownIndex = childIndex; } mLastTouchDownX = ev.getX(); mLastTouchDownY = ev.getY(); //mFirstTouchTarget赋值,就是说child处理了事件 newTouchTarget = addTouchTarget(child, idBitsToAssign); alreadyDispatchedToNewTouchTarget = true; break; }
... } if (preorderedList != null) preorderedList.clear(); }
if (newTouchTarget == null && mFirstTouchTarget != null) { ... } } }
// Dispatch to touch targets. //所有子View都没处理事件 if (mFirstTouchTarget == null) { // No touch targets so treat this as an ordinary view. //那么这里穿的child是null,就是调用super.dispatchTouchEvent(event),就是View.dispatchTouchEvent(event) handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS); } else { ... }
... }
... return handled; }


private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel, View child, int desiredPointerIdBits) { final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations // or filtering. The important part is the action, not the contents. final int oldAction = event.getAction(); if (cancel || oldAction == MotionEvent.ACTION_CANCEL) { event.setAction(MotionEvent.ACTION_CANCEL); if (child == null) { //如果所有子view都没有处理,就调用View本身的分发 handled = super.dispatchTouchEvent(event); } else { //分发到子view,同样开始遍历 handled = child.dispatchTouchEvent(event); } event.setAction(oldAction); return handled; }...


3)view的处理过程:主要是onTouchListener、OnTouchEvent、onClick的关系

public boolean dispatchTouchEvent(MotionEvent event) { ...
boolean result = false;
...
if (onFilterTouchEventForSecurity(event)) { if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { result = true; } //noinspection SimplifiableIfStatement ListenerInfo li = mListenerInfo; if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) { //设置了OnTouchListener且onTouch返回 true,则看下面一行 result = true; } //设置了OnTouchListener且onTouch返回 true就不会走onTouchEvent了 if (!result && onTouchEvent(event)) { result = true; } }
...
return result; }


public boolean onTouchEvent(MotionEvent event) { final float x = event.getX(); final float y = event.getY(); final int viewFlags = mViewFlags; final int action = event.getAction();

final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED) { if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { setPressed(false); } mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; // A disabled view that is clickable still consumes the touch // events, it just doesn't respond to them. //即使disabled,也是可点击也会消费事件 return clickable; } if (mTouchDelegate != null) { if (mTouchDelegate.onTouchEvent(event)) { return true; } }
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { switch (action) { case MotionEvent.ACTION_UP: ...
// Only perform take click actions if we were in the pressed state if (!focusTaken) { // Use a Runnable and post this rather than calling // performClick directly. This lets other visual state // of the view update before click actions start. if (mPerformClick == null) { mPerformClick = new PerformClick(); } if (!post(mPerformClick)) { //走onClick了 performClickInternal(); } } }
... break;
case MotionEvent.ACTION_DOWN: ... break; case MotionEvent.ACTION_MOVE: ... break; }
return true; }
return false; }


二、滑动冲突


1、冲突场景

ViewGroup的滑动和子view的滑动有冲突。

外部横向,里面竖向,那就是看外部啥时候拦截。

外部里面都是相同方向,那就要看具体的业务规则了。


2、解决原理

因为ViewGroup的onInterceptTouchEvent默认是不拦截的,所以:

解决滑动冲突的要点重写onInterceptTouchEvent,根据冲突场景的规则来 判断是否拦截,即isIntercept的赋值规则。其他代码不动即可。

(还有个内部拦截法,用子view调用parent.requestDisallowInterceptTouchEvent(true),就不让parent拦截


@Override public boolean onInterceptTouchEvent(MotionEvent motionEvent) { //解决滑动冲突 boolean isIntercept = false;
int x = (int) motionEvent.getX(); int y = (int) motionEvent.getY();
switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: //down不能拦截,因为已拦截就都给你了。 mLastXIntercept = x; mLastYIntercept = y; break; case MotionEvent.ACTION_MOVE:
//是横向的滑动 boolean isHorizontal = Math.abs(x - mLastXIntercept) > Math.abs(y - mLastYIntercept);
//解决滑动冲突的要点:根据冲突场景的规则来 判断是否拦截,即isHorizontal如果取值 if (isHorizontal) { //此处一旦拦截,后面的ACTION就不会在调用onInterceptTouchEvent isIntercept = true; } break; case MotionEvent.ACTION_UP: //up不能拦截,因为拦截了没啥意义。因为如果前面拦截了Down,那自然Up也会给到。 //另外,如果只拦截了UP,那子view即使处理了其他事件,那也不会走onClick。 break; }
Log.i(TAG, "onInterceptTouchEvent: isIntercept:" + isIntercept);
//此处要记录下 拦截时的 开始的 触摸点(仅用于下面onTouchEvent处理滑动使用) mLastX = mLastXIntercept; mLastY = mLastYIntercept;
mLastXIntercept = x; mLastYIntercept = y;
return isIntercept; }

3、例子

请查看之前写的一篇横向滑动View:<自定义ViewGroup实例:横向滑动HorizontalView>。(可点击“阅读原文”查看文章链接)


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存